// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct FixupConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shebang: Option<Vec<FixupShebangConfig>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rename: Option<Vec<FixupRenameConfig>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FixupShebangConfig {
    pub files: Vec<String>,
    pub interpreter: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct FixupRenameConfig {
    pub from: String,
    pub to: String,
}

impl FixupConfig {
    pub fn spec_hash(&self, hasher: &mut Sha256) {
        if let Some(shebang_fixes) = &self.shebang {
            for fix in shebang_fixes {
                fix.spec_hash(hasher);
            }
        }
        if let Some(rename_fixes) = &self.rename {
            for fix in rename_fixes {
                fix.spec_hash(hasher);
            }
        }
    }
}

impl FixupShebangConfig {
    pub fn spec_hash(&self, hasher: &mut Sha256) {
        hasher.update(self.interpreter.as_bytes());
        for file in &self.files {
            hasher.update(file.as_bytes());
        }
    }
}

impl FixupRenameConfig {
    pub fn spec_hash(&self, hasher: &mut Sha256) {
        hasher.update(self.from.as_bytes());
        hasher.update(self.to.as_bytes());
    }
}
